import 'package:dance_todo/db/bean_event.dart';
import 'package:dance_todo/db/bean_record.dart';
import 'package:dance_todo/main.dart';
import 'package:dance_todo/res/res_keys.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class ScheduleCtrl extends GetxController {
  static ScheduleCtrl get to => Get.find();

  final events = <Event>[].obs;
  final records = <Record>[].obs;
  final eventBox = objectbox.store.box<Event>();
  final selectRecordId = 0.obs;

  @override
  void onInit() {
    super.onInit();
    queryEvents();
    getSelectRecordId();
  }

  //notice 获取每一天对应的记录
  void queryRecordsForDay(DateTime day) {
    records.value= Record.queryRecords(recordBox,day);
    records.refresh();
  }

  ///查询事件
  void queryEvents() {
    final queryEvents = eventBox.getAll();
    print("查询完毕，当前事件：${queryEvents.length}");
    if (queryEvents.isNotEmpty) {
      events.value = queryEvents;
      events.refresh();
    }
  }

  void createEvent(Event event) {
    int result = eventBox.put(event);
    print("createEvent result is $result");
  }

  void getSelectRecordId() {
    final box = GetStorage();
    int? recordId = box.read<int>(KEY_SELECT_RECORD_ID);
    recordId ??= 0;
    selectRecordId.value = recordId;
    selectRecordId.refresh();
  }

  void saveSelectRecordId(int recordId) {
    selectRecordId.value = recordId;
    selectRecordId.refresh();
    final box = GetStorage();
    box.write(KEY_SELECT_RECORD_ID, recordId);
  }

  //notice 添加记录到今日列表
  void addRecordToToday(Event event,DateTime dateTime) {
    Record record=Record();
    record.name=event.name;
    record.doneCount=0;
    record.totalCount=event.totalCount;
    record.date=dateTime;
    record.eventId=event.id;
    recordBox.put(record);
  }
}
